<template>
  <div id="demoCanvas" ref="demoCanvas" ></div>
</template>
<script setup lang="ts">
  import { onMounted, ref, nextTick } from 'vue';
  import SVGA from "svgaplayerweb";
import { Player } from 'svgaplayerweb';
  const demoCanvas:any = ref();
  const props = defineProps({
    svgaUrl:{
      type:String, // svg地址
      default:''
    },
    loops:{
      type:Number, // 播出次数
      default:1
    },
  })
  const $emit = defineEmits(['svgend','svgload'])
  const getAssetsFile = (url: string) => {
    return new URL(`../assets/svga/${url}`, import.meta.url).href
  }
  let player:any
  let parser:any
  const initialize = ()=> {
    player = new SVGA.Player(demoCanvas.value);
    parser = new SVGA.Parser();
    player.loops = props.loops;
    const svgaUrl = getAssetsFile(props.svgaUrl)
    parser.load(svgaUrl,(videoItem:any) => {
      player.setVideoItem(videoItem);
      // player.startAnimation(false);
        player.stopAnimation()
        $emit('svgload');
        player.onFinished(()=>{
          $emit('svgend');
        });
      },
      (e:any) => {
        console.log("svga fail", e);
      }
    );
  };
  const startAnimation = ()=>{
    if(parser) player.startAnimation(false);
  }
  const pauseAnimation = ()=>{
    if(parser) player.stopAnimation()
  }
  onMounted(() => {
    nextTick(()=>{
      initialize()
    })
  })
  defineExpose({
    pauseAnimation,
    startAnimation
  })
</script>
<style>
  #demoCanvas {
    width: 100%;
    height: 100%;
  }
</style>
